<!-- index.vue：机构管理的主页面 -->
<template>
  <div class="org-management" :class="{ 'detail-open': orgDetailPanelVisible }">
    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="机构层级">
            <el-select v-model="searchForm.org_level" placeholder="请选择机构层级" clearable>
              <el-option label="总部（学校）" value="1" />
              <el-option label="分部（学院）" value="2" />
              <el-option label="部门（班级/年级）" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button v-if="searchForm.org_id" type="info" @click="goBackToParent">返回上级</el-button>
            <el-button type="success" @click="showAddOrgDialog">添加机构</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 机构列表 -->
    <div class="org-list">
      <el-card>
        <div slot="header" class="card-header">
          <span>机构列表</span>
          <span class="current-level">
            当前层级：{{ getOrgLevelTagText(parseInt(searchForm.org_level)) }}
          </span>
        </div>

        <el-table v-loading="loading" :data="orgList" style="width: 100%">
          <el-table-column prop="orgId" label="机构ID" width="280" show-overflow-tooltip />
          <el-table-column prop="orgName" label="机构名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="orgType" label="机构类型" width="120">
            <template slot-scope="scope">
              <el-tag :type="getOrgTypeTagType(scope.row.orgType)">
                {{ getOrgTypeTagText(scope.row.orgType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="orgLevel" label="机构层级" width="120">
            <template slot-scope="scope">
              <el-tag :type="getOrgLevelTagType(scope.row.orgLevel)">
                {{ getOrgLevelTagText(scope.row.orgLevel) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="contactPhone" label="联系电话" width="150" show-overflow-tooltip />
          <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
              <el-tag v-else-if="scope.row.status === 2" type="danger">停用</el-tag>
              <el-tag v-else type="warning">未知</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sortOrder" label="排序" width="80" />
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="updatedAt" label="更新时间" width="180">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.updatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <div class="operation-buttons">
                <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="openOrgDetailPanel(scope.row)"
                >
                  详情
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            :current-page="1"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="10"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 机构详情右侧面板（顶部：基本信息；中部：机构树；底部：操作） -->
    <div v-if="orgDetailPanelVisible && orgDetail" class="right-side-detail-panel">
      <div class="detail-header">
        <div class="header-left">
          <el-button type="text" class="back-btn" icon="el-icon-arrow-right" @click="closeOrgDetailPanel">收起</el-button>
        </div>
        <div class="header-center">
          <h1 class="header-title">机构详情</h1>
        </div>
        <div class="header-right" />
      </div>

      <div class="detail-content">
        <div class="info-section">
          <h3 class="info-title">机构信息</h3>
          <div class="org-brief">
            <div class="org-brief__name">{{ orgDetail.orgName }}</div>
            <div class="org-brief__tags">
              <el-tag size="small" :type="getOrgTypeTagType(orgDetail.orgType)">{{ getOrgTypeLabel(orgDetail.orgType) }}</el-tag>
              <el-tag size="small" :type="getOrgLevelTagType(parseInt(orgDetail.orgLevel))">{{ getOrgLevelLabel(orgDetail.orgLevel) }}</el-tag>
              <el-tag size="small" :type="orgDetail.status === 1 ? 'success' : (orgDetail.status === 2 ? 'danger' : 'warning')">{{ getStatusText(orgDetail.status) }}</el-tag>
            </div>
            <div class="org-brief__meta">
              <div>机构ID：{{ orgDetail.orgId }}</div>
              <div>父级机构id：{{ orgDetail.parentId || '-' }}</div>
              <div>机构地址：{{ orgDetail.address || '-' }}</div>
              <div>联系电话：{{ orgDetail.contactPhone || '-' }}</div>
              <div>创建时间：{{ formatDateTime(orgDetail.createdAt) }}</div>
              <div>更新时间：{{ formatDateTime(orgDetail.updatedAt) }}</div>
            </div>
          </div>
        </div>

        <div class="info-section">
          <h3 class="info-title">机构树</h3>
          <el-tree
            v-loading="orgTreeLoading"
            :data="orgTree"
            node-key="id"
            :props="{ children: 'children', label: 'label' }"
            :default-expand-all="true"
            highlight-current
            class="org-tree"
          >
            <span slot-scope="{ data }" class="org-tree-node">
              <span class="org-tree-name">{{ data.label }}</span>
              <el-button type="text" size="mini" class="ml8" @click.stop="openOrgDetailFromTree(data)">详情</el-button>
            </span>
          </el-tree>
        </div>

        <div class="info-section">
          <h3 class="info-title">操作</h3>
          <div class="operation-buttons-container">
            <el-button type="primary" size="mini" @click="editOrgFromDetail">编辑基本信息</el-button>
            <el-button type="primary" plain size="mini" @click="viewAllMembers(orgDetail)">所有成员</el-button>
            <el-button v-if="orgDetail && orgDetail.orgLevel < 3" type="success" size="mini" @click="addChildOrg(orgDetail)">添加子机构</el-button>
            <el-button v-if="orgDetail && orgDetail.orgLevel < 3" type="info" size="mini" @click="viewSubOrgs(orgDetail)">查看子机构</el-button>
            <el-button :type="getStatusButtonType(orgDetail && orgDetail.status)" size="mini" @click="toggleStatus(orgDetail)">
              {{ getStatusButtonText(orgDetail && orgDetail.status) }}
            </el-button>
            <el-button type="danger" size="mini" @click="deleteOrg(orgDetail)">删除</el-button>
            <el-button type="success" size="mini" @click="openBatchImportDialog">批量导入用户</el-button>
            <el-button type="primary" size="mini" @click="openAddUserDialog">添加用户</el-button>
            <el-button type="warning" size="mini" @click="openInviteDialog">生成邀请码</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑机构对话框 -->
    <el-dialog :title="orgDialogTitle" :visible.sync="orgDialogVisible" width="60%">
      <el-form
        ref="orgForm"
        :model="orgForm"
        :rules="orgRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机构名称" prop="orgName">
              <el-input v-model="orgForm.orgName" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构类型" prop="orgType">
              <el-select v-model="orgForm.orgType" placeholder="请选择机构类型" :disabled="isAddingChild">
                <el-option
                  v-for="option in orgTypeOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机构层级" prop="orgLevel">
              <el-select v-model="orgForm.orgLevel" placeholder="请选择机构层级">
                <el-option
                  v-for="option in orgLevelOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  :disabled="isAddingChild && parseInt(option.value) <= parentLevelForChild"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父级机构" prop="parentId">
              <el-select v-model="orgForm.parentId" placeholder="请选择父级机构" clearable :disabled="isAddingChild">
                <el-option
                  v-for="option in parentOrgOptions"
                  :key="option.orgId"
                  :label="option.orgName"
                  :value="option.orgId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="orgForm.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理员邮箱" prop="email">
              <el-input v-model="orgForm.email" placeholder="请输入管理员邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="orgForm.status" placeholder="请选择状态">
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序序号" prop="sortOrder">
              <el-input-number v-model="orgForm.sortOrder" :min="0" :max="999" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="机构地址" prop="address">
          <el-input v-model="orgForm.address" type="textarea" placeholder="请输入机构地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="orgDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrg">保存</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入用户对话框 -->
    <el-dialog title="批量导入用户到机构" :visible.sync="batchImport.visible" width="520px">
      <div>
        <div class="text-muted" style="margin-bottom:8px;">机构ID：{{ orgDetail && orgDetail.orgId }}</div>
        <el-upload
          drag
          action="#"
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handleBatchFileChange"
          :file-list="batchImport.file ? [{ name: batchImport.file.name }] : []"
          accept=".xls,.xlsx"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">仅支持 Excel 文件（.xls, .xlsx）</div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchImport.visible = false">取消</el-button>
        <el-button type="primary" :loading="batchImport.uploading" @click="submitBatchImport">开始导入</el-button>
      </div>
    </el-dialog>

    <!-- 基本信息编辑弹窗：仅编辑机构名称/电话/地址 -->
    <el-dialog title="编辑机构基本信息" :visible.sync="basicEditDialogVisible" width="520px">
      <el-form ref="basicEditForm" :model="basicEditForm" :rules="basicEditRules" label-width="100px">
        <el-form-item label="机构名称" prop="orgName">
          <el-input v-model="basicEditForm.orgName" placeholder="请输入机构名称" />
        </el-form-item>
        <el-form-item label="机构电话" prop="contactPhone">
          <el-input v-model="basicEditForm.contactPhone" placeholder="请输入机构电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="basicEditForm.address" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="basicEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBasicEdit">保存</el-button>
      </div>
    </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户到机构" :visible.sync="addUserDialogVisible" width="420px">
      <div>
        <div class="text-muted" style="margin-bottom:8px;">机构：{{ orgDetail && orgDetail.orgName }}（ID：{{ orgDetail && orgDetail.orgId }}）</div>
        <el-input v-model="addUserForm.userId" placeholder="输入登录账户（可留空自动生成）" clearable />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="addUserLoading" @click="addUserIntoCurrentOrg">确定</el-button>
      </div>
    </el-dialog>

    <!-- 生成邀请码对话框 -->
    <el-dialog title="生成机构邀请码" :visible.sync="inviteDialogVisible" width="520px">
      <div>
        <div class="text-muted" style="margin-bottom:8px;">机构：{{ orgDetail && orgDetail.orgName }}（ID：{{ orgDetail && orgDetail.orgId }}）</div>
        <div class="text-muted" style="margin-bottom:8px;">管理员邮箱：{{ orgDetail && orgDetail.email ? orgDetail.email : '（未配置）' }}</div>
        <el-button type="primary" size="small" :loading="invite.sending" :disabled="!orgDetail || !orgDetail.email" @click="sendInviteEmailCode">发送邮箱验证码</el-button>
        <div style="height:8px" />
        <el-input v-model="invite.codeToken" placeholder="验证码token（若后端启用）" size="small" />
        <div style="margin-top:8px; display:flex; gap:8px;">
          <el-button type="warning" size="small" :loading="invite.loading" @click="generateInviteCode">生成邀请码</el-button>
          <el-button size="small" :disabled="!invite.code" @click="copyInviteCode">复制邀请码</el-button>
        </div>
        <div v-if="invite.code" style="margin-top:8px;">
          <el-alert :closable="false" type="success" show-icon>
            <template slot="title">邀请码：{{ invite.code }}</template>
          </el-alert>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="inviteDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import orgMixin from '@/mixins/orgMixin.js'

export default {
  name: 'OrgManagement',
  mixins: [orgMixin],
  watch: {
    // 监听机构层级变化，自动清空父级机构选择
    'orgForm.orgLevel'(newVal) {
      if (newVal === '1') {
        this.orgForm.parentId = null
      }
    }
  },
  methods: {
    // 分页处理
    handleSizeChange(val) {
      // 由于API返回的是完整列表，这里可以模拟分页
      console.log('每页条数改变:', val)
    },

    handleCurrentChange(val) {
      // 由于API返回的是完整列表，这里可以模拟分页
      console.log('当前页改变:', val)
    }
  }
}
</script>

<style lang="scss" scoped src="@/styles/org.scss"></style>
